package com.pirestupppai.network;

import android.content.Intent;

import com.pirestupppai.base.BaseApplication;
import com.pirestupppai.base.BaseResponse;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.ui.activity.InputPhoneActivity;

import rx.functions.Func1;

/**
 * Retrofit数据预处理
 * 感觉在这里预处理比较好
 * 无法解决同一接口成功和失败data返回格式不同的问题
 * 可以改在Gson解析时预处理,稍麻烦一些
 *
 * @author: xiaoluo
 * @date: 2017-02-28 15:57
 */
public class ResponseFunc<T> implements Func1<BaseResponse<T>, T> {

    @Override
    public T call(BaseResponse<T> tBaseResponse) {
        // 对统一数据进行处理
        // ret: 1 正常，0 有问题, 2 token失效
        if (tBaseResponse.ret == 1) {
            LoginUser.TokenVerity.setToken(tBaseResponse.token);
        } else if (tBaseResponse.ret == 2) {
            LoginUser.TokenVerity.setToken("");
            Intent intent = new Intent(BaseApplication.getAppContext(), InputPhoneActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getAppContext().startActivity(intent);

            throw new APIException(tBaseResponse.info);
        } else if (tBaseResponse.ret == 0) {
            if (tBaseResponse.code == 200) {
                return tBaseResponse.data;
            }
            throw new APIException(tBaseResponse.info);
        }
        return tBaseResponse.data;
    }


}
